package logic

import (
	"Junior_two/subject/order/orderrpc/dao"
	"Junior_two/subject/order/orderrpc/model"
	"context"
	"fmt"
	"github.com/astaxie/beego/orm"
	"net/http"
	"time"

	"Junior_two/subject/order/orderrpc/internal/svc"
	"Junior_two/subject/order/orderrpc/pb/orderRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateLogic) Create(in *orderRpc.CreateRequest) (*orderRpc.CreateResponse, error) {
	// todo: add your logic here and delete this line
	//接受参数 检验参数用户ID是否存在
	if !dao.ReadUserId(in.UserId) {
		return &orderRpc.CreateResponse{
			Msg:  "用户不存在",
			Code: http.StatusResetContent,
		}, nil
	}
	//接受参数 检验参数商品ID是否存在
	if !dao.ReadUGoodId(in.GoodId) {
		return &orderRpc.CreateResponse{
			Msg:  "商品不存在",
			Code: http.StatusResetContent,
		}, nil
	}
	//根据用户id 获取商品数据
	u := dao.GetDataByUserId(in.UserId)
	//根据商品id 获取商品数据
	g := dao.GetDataByGoodId(in.GoodId)
	//判断商品真是库存是否充足
	if g.Num < in.Count {
		return &orderRpc.CreateResponse{
			Msg:  "库存不足",
			Code: http.StatusResetContent,
		}, nil
	}
	fmt.Println(g)
	OrderNum := time.Now().Unix()
	//创建订单
	o := model.Order{
		OrderNum:    OrderNum,
		UserName:    u.Username,
		GoodId:      g.Id,
		Count:       in.Count,
		TotalAmount: g.Price * float64(in.Count),
		CreateTime:  time.Now().Format(time.DateTime),
		Address:     "上海八维",
	}
	if !dao.InsertOrder(&o) {
		return &orderRpc.CreateResponse{
			Msg:  "订单生成失败",
			Code: http.StatusResetContent,
		}, nil
	}
	//订单生成 成功 减少相对应的真是库存
	db := orm.NewOrm()
	g.Num -= in.Count
	_, err := db.Update(&g)
	if err != nil {
		return &orderRpc.CreateResponse{
			Msg:  err.Error(),
			Code: http.StatusResetContent,
		}, nil
	}
	return &orderRpc.CreateResponse{
		Msg:  "订单生成成功",
		Code: http.StatusOK,
	}, nil
}
